<? include '../includes/functions.php'; ?>
<?
ob_start();
session_start();
if (isset($_SESSION['loggedinuser'])) {
    session_destroy();
    session_start();
}
connectdb();
global $con;

//Post Params
$employee_number = $_POST['eno'];
$password_plain = $_POST['pass'];
$password_hash = sha1($password_plain);

$password_hash_res = mysqli_fetch_assoc(
                mysqli_query($con, "SELECT password_hash FROM tms.employee where employee_number=" . $employee_number . ";")
        )["password_hash"];
if ($password_hash_res = $password_hash) {
    $login_successful = true;
} else {
    $login_successful = false;
}


if ($login_successful) {
    $_SESSION['loggedinuser'] = $employee_number;
    $_SESSION['loggedinuserdept'] = mysqli_fetch_assoc(
                    mysqli_query($con, "SELECT name from tms.department where department_id = (SELECT department FROM tms.employee where employee_number=" . $employee_number . ");")
            )["name"];
    $_SESSION['loggedinuserdesig'] = mysqli_fetch_assoc(
                    mysqli_query($con, "SELECT designation FROM tms.employee where employee_number=" . $employee_number . ";")
            )["designation"];
    $_SESSION['loggedinuserishrexec'] = false;
    if ($_SESSION['loggedinuserdesig'] == "Executive" && $_SESSION['loggedinuserdept'] == "HR") {
        $_SESSION['loggedinuserishrexec'] = true;
    }
    $_SESSION['loggedinuserishead'] = false;
    $depthead = mysqli_fetch_assoc(
                    mysqli_query($con, "SELECT department_head from tms.department where department_id = (SELECT department FROM tms.employee where employee_number=" . $employee_number . ");")
            )["department_head"];
    if ($depthead == $_SESSION['loggedinuser']) {
        $_SESSION['loggedinuserishead'] = true;
    }
    $_SESSION["infomessage"] = "Login Successful!";
    header("Location: /index");
}else{
    header("Location: /login.php?retry=true");
}

ob_end_flush();
?>